<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <button @click="goBack" class="btn btn-secondary" style="position: absolute; left: 20px; z-index: 10;">← 返回</button>
      <img src="/logo.svg" alt="Logo" class="logo" />
      <div class="header-icon">
        <!-- 机器人图标 SVG -->
        <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="robotHeaderGradient" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
              <stop offset="50%" style="stop-color:#764ba2;stop-opacity:1" />
              <stop offset="100%" style="stop-color:#8b5cf6;stop-opacity:1" />
            </linearGradient>
          </defs>
          <!-- 机器人头部 -->
          <rect x="8" y="12" width="32" height="24" rx="6" fill="url(#robotHeaderGradient)"/>
          <!-- 天线 -->
          <circle cx="18" cy="8" r="1.5" fill="url(#robotHeaderGradient)"/>
          <circle cx="30" cy="8" r="1.5" fill="url(#robotHeaderGradient)"/>
          <line x1="18" y1="9.5" x2="18" y2="12" stroke="url(#robotHeaderGradient)" stroke-width="1.5"/>
          <line x1="30" y1="9.5" x2="30" y2="12" stroke="url(#robotHeaderGradient)" stroke-width="1.5"/>
          <!-- 眼睛 -->
          <circle cx="16" cy="20" r="2" fill="#ffffff"/>
          <circle cx="32" cy="20" r="2" fill="#ffffff"/>
          <!-- 嘴巴 -->
          <rect x="20" y="28" width="8" height="1.5" rx="0.75" fill="#ffffff" opacity="0.8"/>
          <!-- 身体 -->
          <rect x="12" y="36" width="24" height="6" rx="3" fill="url(#robotHeaderGradient)" opacity="0.8"/>
        </svg>
      </div>
      <span>AI超级智能体</span>
    </div>
    
    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
        <!-- 消息头像 -->
        <div class="message-avatar">
          <div v-if="message.type === 'user'" class="avatar user-avatar">
            <!-- 用户头像 SVG -->
            <svg width="32" height="32" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="userManusGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
                </linearGradient>
              </defs>
              <circle cx="24" cy="24" r="18" fill="white" opacity="0.9"/>
              <circle cx="24" cy="18" r="5" fill="url(#userManusGradient)"/>
              <path d="M13 35c0-6.075 4.925-11 11-11s11 4.925 11 11" fill="url(#userManusGradient)"/>
            </svg>
          </div>
          <div v-else class="avatar ai-avatar">
            <!-- AI机器人头像 SVG -->
            <svg width="32" height="32" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="aiManusGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#a855f7;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#7c3aed;stop-opacity:1" />
                </linearGradient>
              </defs>
              <circle cx="24" cy="24" r="18" fill="white" opacity="0.9"/>
              <path d="M24 16c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8zm0 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm-4 8c0-2.2 1.8-4 4-4s4 1.8 4 4" fill="url(#aiManusGradient)"/>
            </svg>
          </div>
        </div>
        
        <div class="message-wrapper">
          <!-- 如果是步骤消息，显示为多个气泡 -->
          <div v-if="message.isSteps" class="steps-container">
            <div v-for="(step, stepIndex) in message.steps" :key="stepIndex" class="message-content step-bubble">
              <div class="step-header">{{ step.header }}</div>
              <div class="step-content">{{ step.content }}</div>
            </div>
          </div>
          <!-- 普通消息显示 -->
          <div v-else class="message-content">
            {{ message.content }}
          </div>
        </div>
      </div>
      
      <!-- 加载指示器 -->
      <div v-if="isLoading" class="message ai">
        <div class="message-avatar">
          <div class="avatar ai-avatar">
            <!-- AI机器人头像 SVG -->
            <svg width="32" height="32" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="aiManusLoadingGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#a855f7;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#7c3aed;stop-opacity:1" />
              </linearGradient>
            </defs>
            <circle cx="24" cy="24" r="18" fill="white" opacity="0.9"/>
            <path d="M24 16c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8zm0 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm-4 8c0-2.2 1.8-4 4-4s4 1.8 4 4" fill="url(#aiManusLoadingGradient)"/>
          </svg>
          </div>
        </div>
        <div class="message-wrapper">
          <div class="message-content">
            正在思考中...
          </div>
        </div>
      </div>
    </div>
    
    <!-- 聊天输入区域 -->
    <div class="chat-input">
      <input 
        v-model="inputMessage" 
        @keyup.enter="sendMessage" 
        placeholder="请输入您的问题..." 
        :disabled="isLoading"
        ref="messageInput"
      />
      <button @click="sendMessage" :disabled="isLoading || !inputMessage.trim()">
        发送
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ManusApp',
  data() {
    return {
      // 聊天消息列表
      messages: [],
      // 输入框内容
      inputMessage: '',
      // 是否正在加载
      isLoading: false,
      // SSE连接
      eventSource: null
    }
  },
  
  mounted() {
    // 发送欢迎消息
    this.addWelcomeMessage()
  },
  
  beforeUnmount() {
    // 组件销毁前关闭SSE连接
    this.closeEventSource()
  },
  
  methods: {
    /**
     * 添加欢迎消息
     */
    addWelcomeMessage() {
      this.messages.push({
        type: 'ai',
        content: '你好！我是AI超级智能体，能够帮助您处理各种复杂任务和问题。请告诉我您需要什么帮助！🤖'
      })
    },
    
    /**
     * 发送消息
     */
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) {
        return
      }
      
      const userMessage = this.inputMessage.trim()
      this.inputMessage = ''
      
      // 添加用户消息到聊天记录
      this.messages.push({
        type: 'user',
        content: userMessage
      })
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      // 开始加载
      this.isLoading = true
      
      try {
        // 调用Manus接口
        await this.callManusSSE(userMessage)
      } catch (error) {
        console.error('发送消息失败:', error)
        this.messages.push({
          type: 'ai',
          content: '抱歉，服务暂时不可用，请稍后再试。'
        })
        this.isLoading = false
      }
    },
    
    /**
     * 调用AI超级智能体SSE接口
     */
    async callManusSSE(message) {
      // 关闭之前的连接
      this.closeEventSource()
      
      // 根据环境变量设置 API 基础 URL
      const API_BASE_URL = process.env.NODE_ENV === 'production'
        ? '/api' // 生产环境使用相对路径，适用于前后端部署在同一域名下
        : 'http://localhost:8123/api' // 开发环境指向本地后端服务
      
      // 构建SSE URL
      const baseUrl = `${API_BASE_URL}/ai/manus/chat`
      const params = new URLSearchParams({
        message: message
      })
      const url = `${baseUrl}?${params}`
      
      // 创建EventSource连接
      this.eventSource = new EventSource(url)
      
      // 用于累积AI回复内容
      let aiResponse = ''
      let aiMessageIndex = -1
      
      // 监听消息事件
      this.eventSource.onmessage = (event) => {
        const data = event.data
        
        if (data === '[DONE]') {
          // 流式传输结束
          this.isLoading = false
          this.closeEventSource()
          return
        }
        
        // 累积AI回复内容
        aiResponse += data
        
        // 如果是第一次接收到数据，创建AI消息
        if (aiMessageIndex === -1) {
          const messageObj = this.parseStepsMessage(aiResponse)
          this.messages.push({
            type: 'ai',
            ...messageObj
          })
          aiMessageIndex = this.messages.length - 1
        } else {
          // 更新AI消息内容
          const messageObj = this.parseStepsMessage(aiResponse)
          this.messages[aiMessageIndex] = {
            type: 'ai',
            ...messageObj
          }
        }
        
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
      
      // 监听错误事件
      this.eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error)
        this.isLoading = false
        this.closeEventSource()
        
        if (aiMessageIndex === -1) {
          this.messages.push({
            type: 'ai',
            content: '抱歉，连接出现问题，请稍后再试。'
          })
        }
      }
      
      // 监听连接打开事件
      this.eventSource.onopen = () => {
        console.log('SSE连接已建立')
      }
    },
    
    /**
     * 关闭EventSource连接
     */
    closeEventSource() {
      if (this.eventSource) {
        this.eventSource.close()
        this.eventSource = null
      }
    },
    
    /**
     * 滚动到聊天底部
     */
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    
    /**
     * 解析步骤消息
     * 检测是否包含步骤格式（Step 1:, Step 2: 等），如果是则分解为多个步骤
     */
    parseStepsMessage(content) {
      // 更强大的步骤模式匹配：支持Step1:, Step 1:, Step1：, Step 1： 等格式
      const stepPattern = /Step\s*(\d+)\s*[：:]/gi
      const matches = [...content.matchAll(stepPattern)]
      
      if (matches.length === 0) {
        // 不是步骤格式，返回普通消息
        return {
          isSteps: false,
          content: content
        }
      }
      
      // 分割步骤
      const steps = []
      
      for (let i = 0; i < matches.length; i++) {
        const match = matches[i]
        const stepNumber = match[1]
        const stepStart = match.index
        const stepHeaderEnd = stepStart + match[0].length
        
        // 确定步骤内容的结束位置
        let stepEnd
        if (i < matches.length - 1) {
          // 不是最后一个步骤，内容到下一个步骤开始
          stepEnd = matches[i + 1].index
        } else {
          // 最后一个步骤，内容到字符串结束
          stepEnd = content.length
        }
        
        // 提取步骤内容
        const stepContent = content.substring(stepHeaderEnd, stepEnd).trim()
        
        // 创建步骤对象
        steps.push({
          header: `Step ${stepNumber}:`,
          content: stepContent
        })
      }
      
      // 过滤掉空内容的步骤
      const validSteps = steps.filter(step => step.content.length > 0)
      
      return {
        isSteps: validSteps.length > 0,
        steps: validSteps
      }
    },
    
    /**
     * 返回主页
     */
    goBack() {
      this.closeEventSource()
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
/* 组件特定样式已在全局样式中定义 */
</style>